package io.renren.modules.sys.controller;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import io.renren.common.utils.R;
import io.renren.modules.sys.entity.ColumnsInfoExcel;
import io.renren.modules.sys.service.ColumnsInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;


/**
 * 导出EXCEL
 *
 * @author zhangfn
 * @date 2020-06-05 10:55:20
 */
@Controller
@RequestMapping("sys/excel")
public class EXCELController {
    @Autowired
    private ColumnsInfoService columnsInfoService;

    @Value("${file.excel}")
    private String excelFile;

    /**
     * 导出表的列信息到excel
     *
     * @param tableid
     * @return
     */
    @GetMapping(value = "/exportEXCEL/{tableid}/{tableName}")
    @ResponseBody
    public R taskInfo(@PathVariable String tableid, @PathVariable String tableName) {


        //根据表的ID查询表里的列
        List<ColumnsInfoExcel> columnsInfo = columnsInfoService.getByTableid(tableid);

        //指定文件输出位置
        OutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream(excelFile + tableName + ".xlsx");
            ExcelWriter excelWriter = EasyExcelFactory.getWriter(outputStream);
            //将要输出的内容填充到Sheet里
            Sheet sheet = new Sheet(1, 0, ColumnsInfoExcel.class);
            //设置sheet表名
            sheet.setSheetName(tableName);
            /**
             * 写数据到Write上下文中
             * 第一个参数：要写入的内容
             * 第二个参数：要写入的sheet目标
             */
            excelWriter.write(columnsInfo, sheet);
            excelWriter.finish();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return R.ok();
    }

}
